package com.aidong.service;

/**
 * Created by john on 16-11-3.
 */
import com.aidong.cache.ItemCache;
import com.aidong.dao.wills.SmsListDao;
import com.aidong.model.wills.SmsList;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;

@Service
public class SmsSendService implements Runnable {
    protected Logger log = Logger.getLogger(this.getClass());
    private Thread thread = new Thread(this);
    private boolean isRun = true;
    @Resource
    protected SmsListDao smsListDao;
    @Resource
    protected ItemCache cache;

    public SmsSendService() {
        this.thread.setDaemon(true);
        this.thread.start();
    }

    public void runNow() {
        if(!this.thread.isAlive()) {
            this.log.warn("SmsSendService thread hang??");
            this.thread = new Thread(this);
            this.thread.setDaemon(true);
            this.thread.start();
        }

        this.thread.interrupt();
    }

    public boolean sendNow(SmsList sms) {
        StringBuilder msg = new StringBuilder();
        StringBuilder taskId = new StringBuilder();
        if(this.sendSms(sms.getMobile(), sms.getSmsText(), msg, taskId)) {
            sms.setStatus(Integer.valueOf(1));
            sms.setTaskId(taskId.toString());
        } else {
            sms.setStatus(Integer.valueOf(3));
        }

        sms.setSendTime(new Date());
        sms.setSendResult(msg.toString());
        return sms.getStatus().intValue() == 1;
    }

    public boolean isRun() {
        return this.isRun;
    }

    public void setRun(boolean run) {
        this.isRun = run;
    }

    public void run() {
        this.sleep();
        if("stop".equalsIgnoreCase(this.getSetting("sms.active"))) {
            this.isRun = false;
        }

        while(true) {
            try {
                this.send();
                this.getStat();
            } catch (Exception var2) {
                this.log.error("SmsSendService thread run error", var2);
            }

            this.sleep();
        }
    }

    private void sleep() {
        try {
            Thread.sleep(300000L);
        } catch (InterruptedException var2) {
            this.log.info(var2.getMessage());
        }

    }

    private void send() {
        label34:
        while(true) {
            if(this.isRun) {
                List list = this.smsListDao.getNotSendList(10);
                if(list != null && list.size() != 0) {
                    StringBuilder msg = new StringBuilder();
                    StringBuilder taskId = new StringBuilder();
                    Iterator i$ = list.iterator();

                    while(true) {
                        if(!i$.hasNext()) {
                            continue label34;
                        }

                        SmsList sms = (SmsList)i$.next();
                        if(msg.length() > 0) {
                            msg.delete(0, msg.length());
                        }

                        if(taskId.length() > 0) {
                            taskId.delete(0, taskId.length());
                        }

                        if(this.sendSms(sms.getMobile(), sms.getSmsText(), msg, taskId)) {
                            sms.setStatus(Integer.valueOf(1));
                            sms.setTaskId(taskId.toString());
                        } else {
                            sms.setStatus(Integer.valueOf(3));
                        }

                        sms.setSendTime(new Date());
                        sms.setSendResult(msg.toString());
                        this.smsListDao.updateStatus(sms);
                    }
                }
            }

            return;
        }
    }

    private void getStat() {
        if(this.isRun) {
            List list = this.getSendStatus();
            if(list != null && list.size() > 0) {
                Iterator i$ = list.iterator();

                while(i$.hasNext()) {
                    SmsList sms = (SmsList)i$.next();
                    this.smsListDao.updateRecvStatus(sms);
                }
            }
        }

    }

    protected boolean sendSms(String mobile, String content, StringBuilder rep, StringBuilder taskId) {
        boolean ret = false;
        String msg = null;
        String smsUrl = this.getSetting("sms.callurl");
        String param = "action=send&userid=" + this.encode(this.getSetting("sms.userid")) + "&account=" + this.encode(this.getSetting("sms.account")) + "&password=" + this.encode(this.getSetting("sms.password")) + "&mobile=" + this.encode(mobile) + "&content=" + this.encode(content) + "&sendTime=&extno=";

        try {
            URL e = new URL(smsUrl);
            HttpURLConnection http = (HttpURLConnection)e.openConnection();
            http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
            http.setConnectTimeout(30000);
            http.setReadTimeout('\uea60');
            http.setRequestMethod("POST");
            http.setDoOutput(true);
            OutputStream os = http.getOutputStream();
            os.write(param.getBytes("utf-8"));
            os.flush();
            os.close();
            this.log.debug(http.getRequestMethod() + " " + smsUrl + " -> " + param);
            if(http.getResponseCode() != 200) {
                this.log.warn("http responseCode: " + http.getResponseCode() + "-" + http.getResponseMessage() + "  url:" + e);
                ret = false;
                msg = http.getResponseMessage();
            } else {
                InputStream is = http.getInputStream();
                char[] cc = new char[1024];
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
                StringBuilder sb = new StringBuilder();

                int len;
                while((len = br.read(cc)) != -1) {
                    sb.append(cc, 0, len);
                }

                br.close();
                this.log.debug(sb.toString());

                try {
                    Document e1 = DocumentHelper.parseText(sb.toString());
                    Element root = e1.getRootElement();
                    ret = "Success".equalsIgnoreCase(root.element("returnstatus").getText());
                    msg = root.element("message").getText();
                    if(ret) {
                        taskId.append(root.element("taskID").getText());
                    }
                } catch (Exception var19) {
                    ret = false;
                    msg = "返回数据无法识别";
                }
            }

            http.disconnect();
        } catch (Exception var20) {
            this.log.error("callUrl: " + smsUrl, var20);
            msg = var20.getMessage();
        }

        rep.append(msg);
        return ret;
    }

    protected List<SmsList> getSendStatus() {
        ArrayList list = null;
        String msg = null;
        String smsUrl = this.getSetting("sms.statusurl");
        String param = "action=query&userid=" + this.encode(this.getSetting("sms.userid")) + "&account=" + this.encode(this.getSetting("sms.account")) + "&password=" + this.encode(this.getSetting("sms.password"));

        try {
            URL e = new URL(smsUrl);
            HttpURLConnection http = (HttpURLConnection)e.openConnection();
            http.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
            http.setConnectTimeout(30000);
            http.setReadTimeout('\uea60');
            http.setRequestMethod("POST");
            http.setDoOutput(true);
            OutputStream os = http.getOutputStream();
            os.write(param.getBytes("utf-8"));
            os.flush();
            os.close();
            this.log.debug(http.getRequestMethod() + " " + smsUrl + " -> " + param);
            if(http.getResponseCode() != 200) {
                this.log.warn("http responseCode: " + http.getResponseCode() + "-" + http.getResponseMessage() + "  url:" + e);
                msg = http.getResponseMessage();
            } else {
                InputStream is = http.getInputStream();
                char[] cc = new char[1024];
                BufferedReader br = new BufferedReader(new InputStreamReader(is, "utf-8"));
                StringBuilder sb = new StringBuilder();

                int len;
                while((len = br.read(cc)) != -1) {
                    sb.append(cc, 0, len);
                }

                br.close();
                this.log.debug(sb.toString());

                try {
                    Document e1 = DocumentHelper.parseText(sb.toString());
                    Element root = e1.getRootElement();
                    List ls = root.elements("statusbox");
                    if(ls != null && ls.size() > 0) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        list = new ArrayList();

                        SmsList sms;
                        for(Iterator i$ = ls.iterator(); i$.hasNext(); list.add(sms)) {
                            Element el = (Element)i$.next();
                            sms = new SmsList();
                            sms.setMobile(el.element("mobile").getText());
                            sms.setTaskId(el.element("taskid").getText());
                            sms.setStatus(Integer.valueOf("10".equalsIgnoreCase(el.element("status").getText())?2:3));
                            sms.setSendResult(el.element("errorcode").getText());

                            try {
                                sms.setRecvTime(sdf.parse(el.element("receivetime").getText()));
                            } catch (Exception var21) {
                                ;
                            }
                        }
                    }
                } catch (Exception var22) {
                    this.log.error(var22);
                    msg = "返回数据无法识别";
                }
            }

            http.disconnect();
        } catch (Exception var23) {
            this.log.error("callUrl: " + smsUrl, var23);
            msg = var23.getMessage();
        }

        return list;
    }

    private String encode(Integer nn) {
        return nn == null?null:this.encode(String.valueOf(nn));
    }

    private String encode(String str) {
        String encoded = "";

        try {
            encoded = URLEncoder.encode(str, "utf-8");
        } catch (Exception var6) {
            this.log.warn("encode:" + str, var6);
        }

        StringBuffer buf = new StringBuffer(encoded.length());

        for(int i = 0; i < encoded.length(); ++i) {
            char focus = encoded.charAt(i);
            if(focus == 42) {
                buf.append("%2A");
            } else if(focus == 43) {
                buf.append("%20");
            } else if(focus == 37 && i + 1 < encoded.length() && encoded.charAt(i + 1) == 55 && encoded.charAt(i + 2) == 69) {
                buf.append('~');
                i += 2;
            } else {
                buf.append(focus);
            }
        }

        return buf.toString();
    }

    protected String getSetting(String keyId) {
        return this.cache.getValue("setting", keyId);
    }
}
